<template>
	<view class="p-4 text-base">
		<view class="text-h4 mb-2">选号参数</view>
		<view class="text-base mb-4">推荐方案：【初选/7列选号池/过滤2】、【初选/前后区选号池/过滤3】、【优选/7列选号池/过滤2】、【优选/前后区选号池/过滤3】中奖率最佳。</view>

		<uni-forms :modelValue="paramFormData">
			<uni-forms-item label="备注信息">
				<uni-easyinput v-model="paramFormData.remark" placeholder="请输入备注" />
			</uni-forms-item>
			<uni-forms-item label="选号模式">
				<uni-data-select v-model="paramFormData.chooseMode"
					:localdata="dltTplModel.ChooseModeData"></uni-data-select>
			</uni-forms-item>
			<uni-forms-item label="号源类型">
				<uni-data-select v-model="paramFormData.poolType"
					:localdata="dltTplModel.PoolTypeData"></uni-data-select>
			</uni-forms-item>
			<uni-forms-item label="号池过滤">
				<uni-data-select v-model="paramFormData.filterLevel"
					:localdata="dltTplModel.FilterLevelData"></uni-data-select>
			</uni-forms-item>
			<uni-forms-item label="号码排除">
				<uni-easyinput v-model="paramFormData.blackNums" placeholder="号码以空格隔开，前后分区以逗号隔开" />
			</uni-forms-item>
			<uni-forms-item label="生成数量">
				<uni-easyinput v-model="paramFormData.quantity" type="number" placeholder="请输入数量" />
			</uni-forms-item>
			<uni-forms-item label="参数多选">
				<uni-data-select v-model="paramFormData.paramList" :localdata="dsParam" multiple></uni-data-select>
			</uni-forms-item>
		</uni-forms>
		<view>
			<button size="mini" @click="onClickPresetParams('nice')">使用推荐方案</button>
			<button size="mini" @click="onClickPresetParams('fav')" class="mx-1">收藏方案</button>
			<button size="mini" @click="onClickPresetParams('recommend')">精华方案</button>
		</view>
		<view class="text-h4 my-2">复盘开奖</view>
		<view class="flex items-center justify-between">
			<view class="me-1">本期：{{activeDrawInfo.lotteryDrawNum}}</view>
			<uni-easyinput v-model="activeDrawInfo.lotteryDrawResult" placeholder="本期开奖号码" />
		</view>
		<view class="flex items-center my-1">
			<view class="me-4">上期：{{prevDrawInfo.lotteryDrawNum}}</view>
			<view>{{prevDrawInfo.lotteryDrawResult}}</view>
		</view>
		<view class="flex items-center justify-between mb-2">
			<view>复盘：</view>
			<uni-data-select :localdata="dsHistory" @change="onChangeHistorySelect"></uni-data-select>
		</view>
		<view class="my-2">
			<button size="mini" type="primary" @click="batchGenerateOrders()">生成号码</button>
			<button size="mini" class="mx-1" @click="onReset()">重置</button>
			<button size="mini" @click="onCopy()">复制</button>
		</view>
		<view class="my-2">
			<button size="mini" @click="onSaveTemp(false)">覆盖暂存</button>
			<button size="mini" class="mx-1" @click="onSaveTemp(true)">追加暂存</button>
			<button size="mini" @click="onClearTemp()">清空暂存</button>
		</view>
		<view v-for="(item, idx) in formList" :key="idx">
			<view class="flex items-center justify-between">
				<uni-title type="h4" :title="`#${idx+1}【${dltTplModel.getParamText(item.param)}】`"></uni-title>
				<text v-if="activeDrawInfo.lotteryDrawResult"
					:class="item.netProfitMoney > 0 ? 'text-red-400' : 'text-green-600'">
					（{{(item.netProfitMoney > 0 ? '盈利' : '亏损') + Math.abs(item.netProfitMoney) + '元'}}）
				</text>
			</view>
			<view class="flex items-center justify-between mb-1">
				<view>号码</view>
				<view>结果</view>
				<view>操作</view>
			</view>
			<view class="flex items-center justify-between" v-for="(item2, idx2) in item.drawList" :key="idx2">
				<view v-html="item2.text"></view>
				<view class="text-error" v-if="item2.status>0">{{`${item2.statusText}(${item2.moneyText})`}}</view>
				<view class="text-error" v-else>{{item2.statusText}}</view>
				<view><button size="mini" type="warn" @click="onDeleteRow(idx, idx2)">删除</button></view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue';

	import DltDataModel from '@/model/DltDataModel';
	import DltOrderModel from '@/model/DltOrderModel';
	import DltTplModel from '@/model/DltTplModel';
	import FsDriver from '@/model/FsDriver';
	import {
		copyText
	} from '@/utils/Utils';

	const fsDriver = new FsDriver();
	const dltTplModel = new DltTplModel();
	const dltDataModel = new DltDataModel();
	const dltOrderModel = new DltOrderModel();
	const dataset = [...dltDataModel.getDataSource()];
	const statDrawal = dltDataModel.getDrawalStat(dataset);
	const weekdays = ['日', '一', '二', '三', '四', '五', '六'];
	const dsHistory = dataset.map((v, i) => {
		return {
			text: `${v.lotteryDrawNum}（${v.lotteryDrawTime.substring(5)} ${weekdays[new Date(v.lotteryDrawTime).getDay()]}）${v.lotteryDrawResult}`,
			value: i
		};
	});

	const dsParam = dltTplModel.getAllTplParams().map(v => {
		return {
			text: dltTplModel.getParamText(v),
			value: v.id
		}
	});

	const prevDrawInfo = ref(dataset.length > 0 ? dataset[0] : {
		lotteryDrawNum: '',
		lotteryDrawResult: ''
	});
	const activeDrawInfo = ref({
		lotteryDrawNum: parseInt(prevDrawInfo.value.lotteryDrawNum) + 1,
		lotteryDrawResult: ''
	});

	const resetParamFormData = {
		remark: '',
		chooseMode: '初选',
		poolType: 'columns',
		filterLevel: "1",
		blackNums: '',
		quantity: 10,
		paramList: [],
	};
	const paramFormData = ref({
		...resetParamFormData
	});

	const formList = ref([]);

	const onReset = function() {
		paramFormData.value = {
			...resetParamFormData
		};
		prevDrawInfo.value = dataset.length > 0 ? dataset[0] : {
			lotteryDrawNum: '',
			lotteryDrawResult: ''
		};
		activeDrawInfo.value = {
			lotteryDrawNum: parseInt(prevDrawInfo.value.lotteryDrawNum) + 1,
			lotteryDrawResult: ''
		}
	}

	const onChangeHistorySelect = function(value) {
		activeDrawInfo.value = dataset[value];
		prevDrawInfo.value = dataset[value + 1];
		paramFormData.value.blackNums = dltDataModel.getBlackNumsByPrevDrawResult(
			statDrawal.statConsecutiveNums, prevDrawInfo.value?.lotteryDrawResult
		).map(v => v.join(' ')).join(', ');
	}

	const allParams = dltTplModel.getAllTplParams();
	const onClickPresetParams = (type) => {
		let data = [];
		if (type == 'nice') {
			paramFormData.value.paramList = ['CC2', 'YC2', 'CF3', 'YF3']
			return;
		}
		if (type == 'fav') {
			data = JSON.parse(fsDriver.get('fav-params') || '[]');
			paramFormData.value.paramList = allParams.filter(v => data.includes(v.id)).map(v => v.id);
			return;
		}
		if (type == 'recommend') {
			data = JSON.parse(fsDriver.get('recommend-params') || '[]');
			paramFormData.value.paramList = allParams.filter(v => data.includes(v.id)).map(v => v.id);
			return;
		}
	}

	const batchGenerateOrders = () => {
		formList.value = [];
		let blackNums = paramFormData.value.blackNums;
		let ticketQuantity = parseInt(paramFormData.value.quantity) < 1 ? 1 : parseInt(paramFormData.value.quantity);
		if (paramFormData.value.paramList.length > 0) {
			dltTplModel.getAllTplParams(blackNums)
				.filter(v => paramFormData.value.paramList.includes(v.id))
				.forEach((param, i) => {
					formList.value.push({
						...dltTplModel.getTplForOrderListItem({
							id: i + 1,
							ticketQuantity: ticketQuantity,
							param
						})
					})
				})
		} else {
			formList.value.push({
				...dltTplModel.getTplForOrderListItem({
					id: 1,
					ticketQuantity: ticketQuantity,
					param: paramFormData.value
				})
			})
		}
		let drawResult = activeDrawInfo.value?.lotteryDrawResult?.trim() || '';
		let prevDrawResult = prevDrawInfo.value?.lotteryDrawResult?.trim() || '';
		let isDraw = drawResult.length > 0;
		let n = formList.value.length;
		for (let formIdx = 0; formIdx < n; formIdx++) {
			formList.value[formIdx].list = [];
			formList.value[formIdx].drawList = [];
			// 初选
			onChooseAuto(formIdx, ticketQuantity);
			// 优选
			if (formList.value[formIdx].param.chooseMode == '优选') {
				formList.value[formIdx].list = dltOrderModel.getBetterNums7(statDrawal, formList.value[formIdx].list,
					'', prevDrawResult, blackNums);
			}
			// 开奖
			formList.value[formIdx].drawList = dltOrderModel.calcOrder(drawResult, formList.value[formIdx].list,
				false, prevDrawResult);
			// 统计
			if (isDraw) {
				formList.value[formIdx].totalIncome = formList.value[formIdx].drawList.map(v => v.money)
					.reduce((a, b) => {
						return parseInt(a) + parseInt(b)
					});
				formList.value[formIdx].netProfitMoney = formList.value[formIdx].totalIncome - (ticketQuantity * 2);
				formList.value[formIdx].maxPrize = dltOrderModel.getMaxPrize(formList.value[formIdx].drawList);
			}
		}
	}

	/**
	 * 机选一注
	 */
	const onChooseAuto = (formIdx, count = 1) => {
		let nums = [],
			n = count == 1 ? count : (count - formList.value[formIdx].list.length);
		let filterLevel = parseInt(formList.value[formIdx].param.filterLevel);
		let poolType = formList.value[formIdx].param.poolType;
		let blackNums = paramFormData.value.blackNums;
		let prevDrawResult = prevDrawInfo.value?.lotteryDrawResult?.trim() || '';
		while (n > 0) {
			nums = dltOrderModel.getRandomNums7(statDrawal, poolType, filterLevel, prevDrawResult, blackNums);
			formList.value[formIdx].list.push(nums[0].join(' ') + ' ' + nums[1].join(' '));
			n--;
		}
	}

	/**
	 * 优选（在机选号码里面继续机选）
	 */
	const onChooseAutoBetter = (formIdx) => {
		if (formList.value[formIdx].list.length == 0) {
			uni.showToast({
				title: '请先选择机选的号码',
				icon: 'error'
			})
			return;
		}
		let blackNums = paramFormData.value.blackNums;
		let prevDrawResult = prevDrawInfo.value?.lotteryDrawResult?.trim() || '';
		formList.value[formIdx].list = dltOrderModel.getBetterNums7(statDrawal, formList.value[formIdx].list,
			prevDrawResult, blackNums);
	}
	const onDeleteRow = (formIdx, idx) => {
		formList.value[formIdx].list.splice(idx, 1);
		if (formList.value[formIdx].drawList.length > 0) {
			formList.value[formIdx].drawList.splice(idx, 1);
		}
	}

	const onCopy = () => {
		copyText(formList.value.map(v => dltTplModel.getParamText(v.param) + '\n' + v.list.join('\n')).join('\n'));
		uni.showToast({
			title: '复制成功',
			icon: 'success'
		})
	}

	const onSaveTemp = (isAppend = true) => {
		let data = [];
		if (isAppend) {
			data = JSON.parse(fsDriver.get('temp-order') || '[]');
		}
		fsDriver.save('temp-order', JSON.stringify(data.concat(...formList.value.map(v => v.list))));
		uni.showToast({
			title: (isAppend ? '追加' : '覆盖') + '暂存成功，可以在【帮助中心】重新获取内容。',
			icon: 'success'
		})
	}
	const onClearTemp = () => {
		uni.showModal({
			title: '提示',
			content: '确定要删除暂存内容吗？',
			success: function(res) {
				if (res.confirm) {
					fsDriver.save('temp-order', '');
				}
			}
		});
	}
</script>

<style>
	:deep(.uni-forms-item) {
		margin-bottom: 4px !important;
	}
</style>